package com.example.tests;

import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;

import java.util.Random;

import org.testng.annotations.Test;

import com.example.utils.SortedListOf;

public class ContactModificationTests extends TestBase{
	
	@Test(dataProvider = "randomValidContactGenerator")
	public void modifySomeContact(ContactInfo contact){
	    
	//...get oldList from database
		SortedListOf<ContactInfo> oldList = app.getContactHelper().getContacts();
	    
	//...select contact to be modified
	    Random rnd = new Random();
	    int index = rnd.nextInt(oldList.size()-1);
	    ContactInfo c = oldList.get(index);
	    
	//...compare data in contact modification form to the database
	    app.getContactHelper().checkFromDB(c);
	    
	//...modify selected contact
	    app.getContactHelper().modifyContact(c, contact);
	  
	//...get newList from UI main page
	    SortedListOf<ContactInfo> newList = app.getContactHelper().getContactsFromUI();

	//...handle contact in oldList if some main modification data is missing
		if (contact.getFirstName() == null){
			contact.withFirstName(oldList.get(index).getFirstName());
		}
		if (contact.getLastName() == null){
			contact.withLastName(oldList.get(index).getLastName());
		}
		if (contact.getEmail() == null){
			contact.withEmail(oldList.get(index).getEmail());
		}
		if (contact.getHomeNumber() == null){
			contact.withHomeNumber(oldList.get(index).getHomeNumber());
		}
		
		//assert that the list in UI main page is updated correctly
		assertThat(newList, equalTo(oldList.without(index).withAdded(contact)));
	}

}
